package com.imooc.sell.controller;


import com.imooc.sell.dataobject.ProductCategory;
import com.imooc.sell.dataobject.ProductInfo;
import com.imooc.sell.service.CategoryService;
import com.imooc.sell.service.ProductInfoService;
import com.imooc.sell.util.ResultVoUtil;
import com.imooc.sell.vo.ProductInfoVo;
import com.imooc.sell.vo.ProductVo;
import com.imooc.sell.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.xml.transform.Result;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 小柯
 * @Date 2019/6/29  19:24
 * 买家商品
 **/
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProductInfoService productInfoService;


    @GetMapping("/list")
    public ResultVo list(){
        //1、查询所有的上架商品
        List<ProductInfo> productInfoList = productInfoService.findUpAll();

        //2、查询所有的类目（一次性查询）

/*        List<Integer> categoryTypeList = new ArrayList<>();
        for (ProductInfo productInfo : productInfoList) {
            categoryTypeList.add(productInfo.getCategoryType());
        }*/
        List<Integer> categoryTypeList = productInfoList.stream().map(e ->
                e.getCategoryType())
                .collect(Collectors.toList());


        List<ProductCategory> ProductCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);

        //3、拼装数据

        List<ProductVo> productVoList = new ArrayList<>();
        for (ProductCategory productCategory : ProductCategoryList) {
            ProductVo productVo = new ProductVo();
            productVo.setCategoryName(productCategory.getCategoryName());
            productVo.setCategoryType(productCategory.getCategoryType());

            List<ProductInfoVo> productInfoVoList = new ArrayList<>();
            for (ProductInfo productInfo : productInfoList) {
                ProductInfoVo productInfoVo = new ProductInfoVo();
                BeanUtils.copyProperties(productInfo, productInfoVo);
                productInfoVoList.add(productInfoVo);
            }
            productVo.setProuctInfoVoList(productInfoVoList);
            productVoList.add(productVo);
        }

        return ResultVoUtil.success(productVoList);
    }
}
